package com.ycb.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.SerializeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.core5.http.message.BasicHeader;

import java.io.File;

/**
 * @author 黄泽群
 * @since 2024-01-19
 */
@Slf4j
public class JdCookieStore {

    private final BasicCookieStore cookieStore ;

    private final String filePath;

    public JdCookieStore(String filePath){
        this.filePath =filePath;
        if (FileUtil.exist(filePath)) {
            byte[] bytes = FileUtil.readBytes(filePath);
            if (ArrayUtil.isNotEmpty(bytes)){
                cookieStore = SerializeUtil.deserialize(bytes);
                log.info("读取Cookie缓存成功");
                log.info("cookies : {}",cookieStore);
                return ;
            }
        }
        cookieStore = new BasicCookieStore();
        log.info("初始化Cookie成功");
    }

    public CookieStore getCookieStore(){
        return cookieStore;
    }

    /**
     * 获取Cookie对象
     * @param cookieName  cookie名称
     * @return {@link Cookie}
     */
    public Cookie getCookie(String cookieName){
        for (Cookie cookie : cookieStore.getCookies()) {
            if (cookie.getName().equalsIgnoreCase(cookieName)) {
                return cookie;
            }
        }
        return null;
    }

    /**
     * 保存Cookie 持久化操作
     */
    public void saveCookie(){
        byte[] serialize = SerializeUtil.serialize(cookieStore);
        File file = FileUtil.writeBytes(serialize,filePath);
        log.info("Cookie缓存成功 {}",file);
    }

    /**
     * 获取所有Cookie请求头
     * @return {@link BasicHeader}
     */
    public BasicHeader getCookieHeader(){
        return new BasicHeader("Cookie", getCookies());
    }

    public String getCookies(){
        StringBuilder sb = new StringBuilder();
        for (Cookie cookie : cookieStore.getCookies()) {
            sb.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
        }
        return sb.toString();
    }

}
